package com.siyoumi.entity;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.siyoumi.component.XRedis;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.mybatispuls.ServiceImplBase;
import com.siyoumi.util.XJson;
import com.siyoumi.util.XLog;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysRoleService
        extends ServiceImplBase<SysRoleMapper, SysRole> {
    static public SysRoleService getBean() {
        return XSpringContext.getBean(SysRoleService.class);
    }

    @Override
    public XReturn saveEntityBefore(InputData inputData, SysRole entity) {
        String systemRole = inputData.input("system_role");
        if ("1".equals(systemRole)) {
            //系统角色
            entity.setRole_x_id("");
        } else {
            entity.setRole_x_id(XHttpContext.getX());
        }
        return super.saveEntityBefore(inputData, entity);
    }

    /**
     * 根据角色获取所有权限
     *
     * @param roleId 角色ID
     * @return 权限数组
     */
    public List<String> getPathsByRole(String roleId, Boolean getCache) {
        SysRoleRouterService app = SysRoleRouterService.getBean();

        String key = getEntityCacheKey("role_path|" + roleId);
        String json = XRedis.getBean().getAndSetData(key, k ->
        {
            QueryWrapper<SysRoleRouter> query = app.q();
            query.eq("roro_role_id", roleId)
                    .select("roro_appr_path");
            List<SysRoleRouter> list = app.mapper().get(query);
            return list.stream().map(SysRoleRouter::getRoro_appr_path).collect(Collectors.toList());

        }, getCache);

        return XJson.parseArray(json, String.class);
    }

    /**
     * 所有角色
     */
    public JoinWrapperPlus<SysRole> getListQuery(InputData inputData) {
        String compKw = inputData.input("compKw");

        JoinWrapperPlus<SysRole> query = join();
        query.in("role_x_id", List.of("", XHttpContext.getX()))
                .orderByAsc("role_order");
        if (XStr.hasAnyText(compKw)) {  //名称
            query.like("role_name", XStr.concat("%", compKw, "%"));
        }

        return query;
    }

    /**
     * 是否存在帐号设置此权限
     *
     * @param roleId
     */
    public Boolean existSetAcc(String roleId) {
        SysAccountService appAcc = SysAccountService.getBean();

        return appAcc.first(appAcc.q().eq("acc_role", roleId)) != null;
    }


    @Override
    public XReturn saveEntityAfter(InputData inputData, SysRole entity) {
        String doSetTree = XHttpContext.input("do_set_tree", "0");
        if (doSetTree.equals("1")) {
            XLog.debug(this.getClass(), "修改权限，先删除->再重新保存");

            String rPath = XHttpContext.input("r_path");

            //删除
            SysRoleRouterService appRoleR = SysRoleRouterService.getBean();
            QueryWrapper<SysRoleRouter> query = appRoleR.q().eq("roro_role_id", entity.getKey());
            appRoleR.remove(query);

            String[] arrPath = rPath.split(",");
            List<SysRoleRouter> list = Arrays.stream(arrPath).map(path -> {
                SysRoleRouter entityRoro = new SysRoleRouter();
                entityRoro.setRoro_x_id(entity.getX())
                        .setRoro_role_id(entity.getKey())
                        .setRoro_appr_path(path);
                entityRoro.setAutoID();
                return entityRoro;
            }).collect(Collectors.toList());

            //批量添加
            appRoleR.saveBatch(list);
        }

        //清缓存
        delEntityCache("apps|" + entity.getKey());
        delEntityCache("role_path|" + entity.getKey());

        return XReturn.getR(0);
    }
}
